package mark.tom.gear.utils

import android.content.Context
import android.content.Intent
import androidx.multidex.MultiDex
import mark.tom.gear.base.callback.CallBack
import java.io.File

/**
 * @Description: MultiDex工具类
 * @Author: ttmk110@163.com
 * @Package: mark.tom.gear.utils
 * @Date: 2021/1/15
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date:
 * </ModifyLog>
 */
object MultiDexUtil {

    fun install(mContext: Context) {
        MultiDex.install(mContext)
    }

    fun startMultiDexActivity(mContext: Context, clz: Class<*>) {
        val intent = Intent(mContext, clz)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        mContext.startActivity(intent)
    }

    /**
     * Description: 检测MultiDex是否加载完成
     * Copyright: Copyright (c) 2021
     * Project: Gear
     * Author: ttmk110@163.com
     * Date: 2021/1/15 3:41 下午
     */
    fun checkUntilLoadDexSuccess(mContext: Context, mCallBack : CallBack<Context, Any>?) {
        val file = getTmpFile(mContext)

        var i = 0
        val waitTime: Long = 100
        try {
            while (file.exists()) {
                Thread.sleep(waitTime)
                if (++i > 50) {
                    throw IllegalStateException()
                }
            }
        } catch (e: Exception) {
            mCallBack?.onFail(mContext)
        }
        mCallBack?.onSuccess(mContext)
    }

    /**
     * Description: 创建multidex安装过程中的临时文件
     * Copyright: Copyright (c) 2021
     * Project: Gear
     * Author: ttmk110@163.com
     * Date: 2021/1/15 3:32 下午
     */
    fun createTmpFile(mContext: Context) {
        val file = getTmpFile(mContext)
        if (!file.exists()) {
            file.createNewFile()
        }
    }

    /**
     * Description: 删除multidex安装过程中的临时文件
     * Copyright: Copyright (c) 2021
     * Project: Gear
     * Author: ttmk110@163.com
     * Date: 2021/1/15 3:33 下午
     */
    fun deleteTmpFile(mContext: Context) {
        val file = getTmpFile(mContext)
        if (file.exists()) {
            file.delete()
        }
    }

    /**
     * Description: multidex安装过程中的临时文件
     * Copyright: Copyright (c) 2021
     * Project: Gear
     * Author: ttmk110@163.com
     * Date: 2021/1/15 3:33 下午
     */
    private fun getTmpFile(mContext: Context): File {
        return File(mContext.cacheDir, "multidex.tmp")
    }

}